package core;

import java.io.Console;
import java.io.IOException;
import java.util.Date;
import java.util.Vector;
import tools.icq.spam.CoreSpam;
import tools.icq.spam.UinChild;
import tools.icq.spam.UinPrime;
import core.remote.CoreRC;
import core.icq.CoreICQ;
import core.xmpp.CoreXMPP;
import tools.*;

/**
 * This is Infhell Main class
 * @author dcrm
 */
public class Main {
    
    public static Vector GROUP = new Vector();
    public static Vector<UinPrime> UIN_PRIMES = new Vector<UinPrime>();
    public static Vector<UinChild> UINS = new Vector<UinChild>();
    public static Vector<ProxyConnection> PROXYZ = new Vector<ProxyConnection>();
    public static Vector<ProxyConnection> SERVER_LOGIN = new Vector<ProxyConnection>();

    public static String[] TIME={"8:30","9:30","10:30","12:00","13:00","14:00","15:00","16:00","17:00"};
    public static String[] TIME_FREE={"9:20","10:20","11:20","12:50","13:50","14:50","15:50","16:50","17:50"};
    public static String[] TIME_NIGHT={"21:00","00:00","6:00"};

    private static String i_Jid_Pwd = "";
    private static String i_phpbb_Pwd = "";

    public static String i_Mode="";
    public static String i_Uin="#";
    private static String i_Pwd = "";
    public static String i_Server="#";
    public static String i_Port="#";
    public static String i_mUin="#";
    public static String TIME_PARSE;
    public static Logger lr;
    public static CoreICQ CORE_INF;
    public static CoreXMPP CORE_XMPP;
    private static int server_port;
    private static String server_host = null;
    private static Console console = null;
    public static CoreSpam coreSpam;


    public static void main(String[] args) throws IOException {
        //CoreICQ Infhell = new CoreICQ("2324312", "=)","login.icq.com",5190,"7360921","","","","");
        pr("\n\n\n/-================_Infhell_===============-\\\n");

        // Console init
        try {
            console = System.console();
        } catch (Exception ex) {System.err.println("| "+ex.getMessage());}

        // Logger init
        pr("|-Start logger.");
        lr = new Logger(); pr(".");
        lr.writeln("\n\n\n/-===_Infhell_["+lr.dt.toLocaleString()+"]===-\\",false); pr(".");
        pr(" OK\n");

        // Config load
        pr("|-Config loading.");
        GlobalConfig.loadConfigFromFile(); pr(".");
        if (GlobalConfig.firstRun) {firstRun();}
        pr(" OK\n");

        // Key load
//        if (GlobalConfig.F_SECURITY_KEY) {
            pr("|-Key loading.");
            GlobalConfig.loadKey();
//        }

        // Start console
        if (args.length>0) {
        pr("|-Starting remote console: ");
             if (args.length==1) {server_port = Integer.parseInt(args[0].toString()); pr("-> "); new CoreRC(server_port);}
             if (args.length>=2) {server_port = Integer.parseInt(args[0].toString()); pr("-> ");server_host=args[1].toString(); new CoreRC(server_port,server_host);}
             if (args.length>=3) {i_Mode = args[2].toString(); }
        }

        // List's load
        try {
            //GlobalConfig.T_GlobalStart=new Date().getTime();
            pr("\n|-Groups loading:");
            GROUP=group_loader();
            pr("\n\n"+((!GROUP.isEmpty())?FucLib.getAllGroup(GROUP,8)+"\n|-Ok!":"|-Error loading groups!")+"\n",true);
            
            TIME_PARSE=FucLib.getDiffTime(GlobalConfig.T_GlobalStart, new Date().getTime());
            pr("|-Loading icq list ("+GlobalConfig.FIL_UIN+") .");
            UINS=AddFucLib.fillUinList(GlobalConfig.FIL_UIN, ";");

            //PROXYZ=AddFucLib.fillProxyList("proxy.txt", ";");
            //SERVER_LOGIN=AddFucLib.fillProxyList(GlobalConfig.FIL_FROXY, ";");
            pr("\n|-All Data List loaded\n");
        } catch (Exception ex) { if (GlobalConfig.F_DEBUG_MSG) {pr("| "+ex.getMessage(),true);} pr(". ERROR!\n");}

        // Start core
        try {
            if (!i_Mode.equals("9")) if (console==null) {System.err.println("Err Console"); i_Mode="6";}
            if (i_Mode.isEmpty()) {
                System.out.print("| SELECT MODE:\n|\t0 - Auto;\n|\t1 - Manual;\n|\t2 - Many Settings;\n|\t3 - Full Settings;\n|\t6 - TestMode\n| \t");
                i_Mode = console.readLine("");
            }
            //if (i_Mode.equals("9")) {/*console*/}
            // Auto
            else if (i_Mode.equals("0")) {
                setPWD(new String(console.readPassword("%s","|-Enter PWD: ")));
                if (i_Pwd.isEmpty()) {System.err.println("Err PWD"); return;}
            }

            // Manual
            else if (i_Mode.equals("1")) {
                i_Uin = console.readLine("|-Enter UIN(or #["+GlobalConfig.x_Uin+"]): ");
                setPWD(new String(console.readPassword("%s","|-Enter PWD: ")));
                if (i_Pwd.isEmpty() || i_Uin.isEmpty()) {System.err.println("Err UIN or PWD"); return;}
            }

            // Many
            else if (i_Mode.equals("2")) {
                i_Uin = console.readLine("|-Enter UIN(or #["+GlobalConfig.x_Uin+"]): ");
                setPWD(new String(console.readPassword("%s","|-Enter PWD: ")));
                i_Server = console.readLine("|-Enter Server(or #["+GlobalConfig.x_Server+"]): ");
                i_Port = console.readLine("|-Enter Port(or #["+GlobalConfig.x_Port+"]): ");
                i_mUin = console.readLine("|-Enter Master UIN(or #["+GlobalConfig.x_mUin+"]): ");
                if (i_Pwd.isEmpty() || i_Uin.isEmpty() || i_Server.isEmpty() || i_Port.isEmpty() || i_mUin.isEmpty())
                    {System.err.println("Err Settings"); return;}
            }

            // TestMode
            else if (i_Mode.equals("6")) {
                //CORE_XMPP = new CoreXMPP(GlobalConfig.i_Jid, GlobalConfig.i_Jid_Master, GlobalConfig.i_Jid_Server, GlobalConfig.i_Jid_Port, GlobalConfig.i_Jid_Login, "1", GlobalConfig.i_Jid_Place);
               // lr.writeln("* UIN: Tester/pgta@jabber.ru;\n* Server:jabber.ru:5222\n+--------------------------------------+\n");
                //CORE_INF = new CoreICQ("499747433", "-pgta+16","login.icq.com",5190,"7360921",null);
                //CoreICQ Tester0 = new CoreICQ("419839747", "-pgta+16","login.icq.com",5190,"7360921","","","","");
                //lr.writeln("* UIN: Tester/7360921;\n* Server:login.icq.com:5190\n+--------------------------------------+\n");
                demonize();
            } else {
                if (i_Uin.equals("#")) {i_Uin=GlobalConfig.x_Uin;}
                if (i_Server.equals("#")) {i_Server=GlobalConfig.x_Server;}
                if (i_Port.equals("#")) {i_Port=GlobalConfig.x_Port;}
                if (i_mUin.equals("#")) {i_mUin=GlobalConfig.x_mUin;}

                //if (i_Uin.equals("#")) {i_Uin=x_Uin;};
                if (!i_Mode.equals("9"))
                {
                    System.out.print("+-=======================================-|\n| UIN: "+i_Uin+"/"+i_mUin+";\n| Server:"+i_Server+":"+i_Port+"\n|-");
                    if (console.readLine("ok? ").equals("ok")){
                        pr("|-Lets'go!\n");
                        pr("* UIN: "+i_Uin+"/"+i_mUin+";\n| Server:"+i_Server+":"+i_Port+"\n+--------------------------------------+\n",true);
                        Thread.sleep(500);
                        poster();
                        System.out.print("\\-=======================================-|\n");
                        Thread.sleep(500);
                        starter(false);
                        //demonize();
                    }
                } else {System.out.print("|-Replay?\n\\-=======================================-/\n"); return;}
            }
        } catch (Exception ex)  {Logger.writelnErr(ex.getMessage());}
    }

    /**
     * By-by.
     */
    public static void exit() {
        lr.writeln("|-STOP at"+new Date().toLocaleString()+"\n\\-====================================-/\n",false);
        lr.stop();
        System.exit(1);
    }

    /**
     * Mini-demonize
     */
    public static void demonize() {
        try {
            System.in.close();
            System.out.close();
        }
        catch(Exception ex) {Logger.writelnErr(ex.getMessage());}
    }

    /**
     * Init config
     */
    public static void firstRun() {
        try {
            pr(". ERROR!\n|-============FIRST_RUN_SETUP=============-|\n",true);
            // Set ICQ pwd
            setConfPWD(GlobalConfig.TYPE_ICQ,"|-Enter ICQ PWD: ");
            printLine();
            setConfPWD(GlobalConfig.TYPE_XMPP,"|-Enter Jabber PWD: ");
            printLine();
            setConfPWD(GlobalConfig.TYPE_PHPBB,"|-Enter PHPBB PWD: ");
            printLine();
            setConfPWD(GlobalConfig.TYPE_CHAT,"|-Enter Chat PWD: ");
            pr("\\-============SETUP_COMPLITE!=============-/");
            GlobalConfig.saveConfigToFile();
            pr("\n\n\nPlease, manual edit: ("+GlobalConfig.CONFILE+")!\n\n");
            exit();
        } catch(Exception ex) {Logger.writelnErr(ex.getMessage()); exit();}
    }

    /**
     * Lets' go!
     * @param post - Accept post forum msg
     */
    public static void starter(boolean post) {
        try {
            pr("Core start:");
            if (!i_Pwd.isEmpty()) {CORE_INF=new CoreICQ(i_Uin, i_Pwd, i_Server,Integer.parseInt(i_Port),i_mUin,null); pr(" ICQ");}
            if (!i_Jid_Pwd.isEmpty()) {CORE_XMPP=new CoreXMPP(GlobalConfig.i_Jid, GlobalConfig.i_Jid_Master, GlobalConfig.i_Jid_Server, GlobalConfig.i_Jid_Port, GlobalConfig.i_Jid_Login, i_Jid_Pwd, GlobalConfig.i_Jid_Place);  pr(" XMPP");}
            if (post) {Main.poster(); pr("POST");}
            pr(" - Complite!");
        } catch(Exception ex) {Logger.writelnErr(ex.getMessage());}
    }

    /**
     * Init icq password
     * @param pwd - password
     */
    public static void setPWD(String pwd) {i_Pwd = pwd;}

    /**
     * Init password
     * @param pwd - password
     * @param TYPE - GlobalConfig.(TYPE_ICQ/TYPE_XMPP/TYPE_PHPBB)
     */
    public static void setPWD(String pwd, int TYPE) {
        switch (TYPE) {
            case GlobalConfig.TYPE_ICQ: i_Pwd = pwd; break;
            case GlobalConfig.TYPE_XMPP: i_Jid_Pwd=pwd; break;
            case GlobalConfig.TYPE_PHPBB: i_phpbb_Pwd=pwd; break;
            default: break;
        }
    }

    /**
     * Init Config password - MD5
     * @param TYPE - GlobalConfig.(TYPE_ICQ/TYPE_XMPP/TYPE_PHPBB
     * @param msg - Input display refix
     */
    public static void setConfPWD(int TYPE, String msg) {
        GlobalConfig.setPWD(new String(console.readPassword("%s",msg)), TYPE);
        System.out.println("|-+MD5:["+GlobalConfig.getPWD(TYPE)+"]+-|");
    }

    /**
     * Print line
     */
    public static void printLine(){
        System.out.println("+------------------------------------------+");
    }

    /**
     * System.out.print + write log
     * @param s - string
     * @param log - accept write in logfile
     */
    public static void pr(String s,boolean log){
        System.out.print(s);
        if (log) {lr.write(s);}
    }

    /**
     * System.out.print
     * @param s - string
     */
    public static void pr(String s){
        pr(s, false);
    }

    /**
     * Posting start info on forum
     */
    public static void poster() {
       if (i_Uin.equals("2324312") && !i_phpbb_Pwd.isEmpty()) {
           pr("\n|-Post info on PGTA forum...\n",true);
           tools.FucLib.postPHPBB3(GlobalConfig.PHPBB_LOGIN_FORM, GlobalConfig.PHPBB_LOGIN,
           i_phpbb_Pwd, GlobalConfig.PHPBB_POST,
           "[size=150]InfHell OnLine : [ "+new Date().toLocaleString()+" ];\nTime ParsingXLS : "+TIME_PARSE+";\nUIN: [b]"+i_Uin+"[/b]"+((!i_Jid_Pwd.isEmpty())?"\nJID: [b]"+GlobalConfig.i_Jid+"[/b]":"")+"[/size]\n[code]"+tools.FucLib.getAllGroup(GROUP,-1)+"[/code]");
           pr("|-Complite!\n",true);
       }
    }

    /**
     * Stop ICQ & XMPP
     */
    public static void stoper() {
        if (CORE_INF!=null) CORE_INF.disconnect(false);
        CORE_INF=null;

        if (CORE_XMPP!=null) CORE_XMPP.disconnect(false);
        CORE_XMPP=null;
    }

    // Freeze
    public static void startCoreSpam() {
        //coreSpam = new CoreSpam(0, false);
        //System.out.print("SpamCore loaded\n");
    }

    /**
     * Load groups
     * @return - Vector Groups
     */
    public static Vector group_loader()
    { return FucLib.getXLSbyFolder(GlobalConfig.DIR_XLS,".xls"); }
/*
    public static Vector group_loader(String patch, String ext)
    { return FucLib.getXLSbyFolder(patch, ext); }*/
    //public static Vector group_loader() {return GROUP;}

}
